<?php

    class Inbox extends ActiveRecord {
        
        function Inbox()
        {
            $conf = array('table'=>DB_PREFIX.'inbox');
            $this->ActiveRecord($conf);
        }
        
        function validate()
        {
            $this->validates_presence_of('form_name');
            foreach( array('form_to','form_cc','form_bcc') as $field )
            {
                $this->_check_each_email($field);
            }
        }
        
        function before_validation()
        {
            // strip off extra commas if there are any
            foreach( array('form_to','form_cc','form_bcc') as $field )
            {
                $value = $this->get($field);
                if (empty($value)) continue;
                $this->set($field,trim($value,", ."));
            }
            
            // strip out any html in the autoresponder            
            if ( $auto = $this->get('autoresponder') )
            {
                $this->set('autoresponder',strip_tags($auto));
            }
            
            if ( $auto = $this->get('autoresponder_subject') )
            {
                $this->set('autoresponder_subject',strip_tags($auto));
            }
        }        
        
        function _check_each_email($field)
        {
            $value = $this->get($field);
            if (empty($value)) return;
            if ( strpos($value,',') === false )
            {
                if ( !is_valid_email($value) )
                {
                    $this->add_error($field,'Contains an invalid email address');
                }
            } else {
                $emails = explode(',',$value);
                foreach( $emails as $email )
                {
                    if (empty($email)) continue;
                    if ( !is_valid_email($email) )
                    {
                        $this->add_error($field,'Contains an invalid email address: '.$email);
                    }
                }
            }
        }
        
        function & get_paged_forms()
        {
            $sql = "SELECT id, form_name `Form Name`, created FROM `{$this->table}` ORDER BY created desc";
            $pager = $this->pager($sql);            
            $pager->header_names = array('id'=>'Form Id');
            $pager->row_key = 'id';
            $pager->id = 'ibx';
            return $pager;
        }
        
        function get_all_forms()
        {
            return $this->db->GetAssoc("SELECT id, form_name FROM `{$this->table}` ORDER BY form_name");
        }
                
    }

?>